package com.quyunshuo.module.home.dialog

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import com.quyunshuo.module.home.databinding.DialogConcentrationBinding
import com.quyunshuo.module.home.databinding.DialogSleepBinding
import com.quyunshuo.module.home.databinding.DialogTestBinding
import com.quyunshuo.module.home.util.dp
import java.util.Calendar

class SleepDialog : BaseDialog<DialogSleepBinding>() {
    companion object {
        fun newInstance(): SleepDialog {
            return SleepDialog()
        }
    }

    private var time: Int = 5

    private var callback: ((Int, Int) -> Unit?)? = null
    fun setCallback(callback: (Int, Int) -> Unit) {
        this.callback = callback
    }

    override fun getGravity(): Int {
        return Gravity.BOTTOM
    }

    override fun createViewBinding(): DialogSleepBinding {
        return DialogSleepBinding.inflate(layoutInflater)
    }

    override fun init(savedInstanceState: Bundle?) {
        binding.comfirm.setOnClickListener {
            dismissAllowingStateLoss()
            callback?.invoke(
                binding.hourPicker.getSelectedValue(),
                binding.minutePicker.getSelectedValue()
            )
        }
        binding.hourPicker.setCallback {
            //进行页面跳转
            computationTime()
        }
        binding.minutePicker.setCallback {
            //进行页面跳转
            computationTime()
        }


    }

    private fun computationTime() {
        val remainingMillis = calculateTimeRemaining(
            binding.hourPicker.getSelectedValue(),
            binding.minutePicker.getSelectedValue()
        )
        // 转换为友好显示
        val seconds = remainingMillis / 1000
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        binding.expectedSleep.text = "预计睡眠时间：$hours 小时 $minutes 分钟"
    }

    fun calculateTimeRemaining(targetHour: Int, targetMinute: Int): Long {
        val calendarNow = Calendar.getInstance()
        val calendarTarget = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, targetHour)
            set(Calendar.MINUTE, targetMinute)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)

            // 如果目标时间已过，则设置为明天
            if (timeInMillis <= calendarNow.timeInMillis) {
                add(Calendar.DATE, 1)
            }
        }
        return calendarTarget.timeInMillis - calendarNow.timeInMillis
    }

    override fun getWidth(): Int {

        if (isTabletDevice(resources.configuration)) {
            return 600.dp
        } else {
            return 360.dp

        }

    }

    override fun cancel(): Boolean {
        return true
    }

}